<script setup>
import {onBeforeUnmount, onMounted, reactive, ref} from "vue";
import {
  codeService,
  getUserInfoService,
  perfectUserInfoService,
  resetEmailService
} from "@/api/user.js";
import {useRouter} from "vue-router";
import {Plus} from "@element-plus/icons-vue";
import {useTokenStore} from "@/stores/token.js";
import {ElMessage} from "element-plus";
import {baseUrl} from "@/utils/request.js";

const tokenStore = useTokenStore();
const title = ref('')

//上传图片请求的后端地址
const uploadUrl = ref(baseUrl+"/file/upload")

//用户信息表单
const userInfoData = reactive({
  id: '',
  username: '',
  email: '',
  newEmail: '',
  captcha: '', //修改邮箱验证码
  userPic: '',
  phone: '',
  qqNumber: '',
  department: '',
  className: '',
  schoolName: '',
  createTime: ''
})
const method = 4 // 4:修改邮箱信息
const countingDown = ref(false)
const countdownSeconds = ref(60)
const countdownText = ref('获取验证码')
//获取用户信息
const getUserInfo = async () => {
  let result = await getUserInfoService();
  userInfoData.id = result.data.id;
  userInfoData.username = result.data.username;
  userInfoData.email = result.data.email;
  userInfoData.userPic = result.data.userPic;
  userInfoData.phone = result.data.phone;
  userInfoData.qqNumber = result.data.qqNumber;
  userInfoData.department = result.data.department;
  userInfoData.className = result.data.className;
  userInfoData.schoolName = result.data.schoolName;
  userInfoData.createTime = result.data.createTime;
}
getUserInfo();


// const rules = ref({
//   username: [
//     {required: true, message: "用户名不能为空", trigger: "blur"},
//     {min: 1, max: 10, message: "用户名长度在1-10之间", trigger: "blur"}
//   ],
//   phone: [
//     {required: true, message: "手机号不能为空", trigger: "blur"},
//     {
//       validator: (rule, value, callback) => {
//         const pattern = /^1[3-9]\d{9}$/;
//         if (!pattern.test(value)) {
//           callback(new Error("手机号格式不正确"))
//         } else {
//           callback()
//         }
//       },
//       trigger: "blur"
//     }
//   ]
// })
//标志用户信息是展示还是修改 0展示，1修改
const isEdit = ref(0);

const perfectInfo = () => {
  isEdit.value = 1;
}
const route = useRouter()
const goBack = () => {
  if (isEdit.value === 1) {
    location.reload();
    getUserInfo();
    isEdit.value = 0;
  } else {
    route.push('/');
  }
}

//文件上传成功回调函数
const uploadSuccess = (result) => {
  userInfoData.userPic = result.data;
  ElMessage.success("上传成功")
}
const beforeUpload = (rawFile) => {
  if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error("图片大小不能超过2M")
    return false
  } else if (rawFile.type !== "image/jpeg" && rawFile.type !== "image/png") {
    ElMessage.error("图片格式不正确")
    return false
  }
  return true
}

const submitInfo = async () => {
  let qqNumberPattern = /^[1-9]\d{4,12}$/;
  let phonePattern = /^1[3-9]\d{9}$/;
  if (userInfoData.username.length === 0) {
    ElMessage.error("用户名不能为空");
    return;
  }
  if (userInfoData.phone.length === 0) {
    ElMessage.error("手机号不能为空");
    return;
  }
  if (userInfoData.qqNumber.length === 0) {
    ElMessage.error("QQ号不能为空");
    return;
  }
  if (userInfoData.department.length === 0) {
    ElMessage.error("所属院系不能为空");
    return;
  }
  if (userInfoData.className.length === 0) {
    ElMessage.error("所属班级不能为空");
    return;
  }
  if (userInfoData.username.length < 1 || userInfoData.username.length > 10) {
    ElMessage.error("用户名长度在1-10之间");
    return;
  }
  if (!qqNumberPattern.test(userInfoData.qqNumber)) {
    ElMessage.error("QQ号格式不正确");
    return;
  }
  if (!phonePattern.test(userInfoData.phone)) {
    ElMessage.error("手机号格式不正确");
    return;
  }
  await perfectUserInfoService(userInfoData);
  ElMessage.success("修改成功");
  await getUserInfo();
  isEdit.value = 0;
}

//修改邮箱
const submitEmail = async ()=>{
  const emailPattern = /^([a-zA-Z0-9._%+-]+)@([a-zA-Z0-9.-]+\.)+[a-zA-Z]{2,}$/;
  const captchaPattern = /^\d{4}$/;
  if (userInfoData.newEmail.length === 0){
    ElMessage.error("新邮箱不能为空");
    return;
  }
  if (userInfoData.captcha.length === 0){
    ElMessage.error("验证码不能为空");
    return;
  }
  if (!emailPattern.test(userInfoData.newEmail)){
    ElMessage.error("邮箱格式不正确");
    return;
  }
  if (!captchaPattern.test(userInfoData.captcha)){
    ElMessage.error("验证码格式不正确");
    return;
  }
  await resetEmailService(userInfoData)
  await getUserInfo();
  userInfoData.newEmail = '';
  userInfoData.captcha = '';
  clearInterval(countdownInterval);
  countdownSeconds.value = 60;
  countdownText.value = '获取验证码';
  countingDown.value = false;
  updateLocalStorage(); // 倒计时结束时也同步到 localStorage
  ElMessage.success("修改成功");
}

//获取验证码
const sendCaptcha =  () => {
  if (userInfoData.newEmail.length === 0){
    ElMessage.error("新邮箱不能为空");
    return;
  }
  codeService(userInfoData.email,method)
  countingDown.value = true
  countdownText.value = `${countdownSeconds.value} 秒后重新获取`
  startCountdown()
  ElMessage.success("验证码发送成功");
}

// 在 setup 函数内
let countdownInterval;
onMounted(() => {
  title.value = route.currentRoute.value.meta.title;
  document.title = title.value;

  // 页面加载时从 localStorage 加载倒计时状态
  const persistedCountdownState = JSON.parse(localStorage.getItem('countdownState'));
  if (persistedCountdownState) {
    countingDown.value = persistedCountdownState.countingDown;
    countdownSeconds.value = persistedCountdownState.secondsRemaining;
    // 如果仍在倒计时，则启动倒计时器
    if (countingDown.value) {
      startCountdown();
    }
  }
});
// 开始倒计时
const startCountdown = () => {
  countdownInterval = setInterval(() => {
    countdownSeconds.value--;
    countdownText.value = `${countdownSeconds.value} 秒后重新获取`;
    updateLocalStorage(); // 每次更新倒计时都同步到 localStorage

    if (countdownSeconds.value <= 0) {
      clearInterval(countdownInterval);
      countdownSeconds.value = 60;
      countdownText.value = '获取验证码';
      countingDown.value = false;
      updateLocalStorage(); // 倒计时结束时也同步到 localStorage
    }
  }, 1000);
}

// 更新本地存储中的倒计时状态
const updateLocalStorage = () => {
  localStorage.setItem(
      'countdownState',
      JSON.stringify({
        countingDown: countingDown.value,
        secondsRemaining: countdownSeconds.value,
      })
  );
};

// 在组件卸载前清除定时器并保存状态
onBeforeUnmount(() => {
  clearInterval(countdownInterval);
  updateLocalStorage();
});
</script>

<template>
  <div class="personal-center-container">
    <div class="tabs">
      <el-tabs type="border-card">
        <el-tab-pane label="个人信息">
          <div class="info">
            <el-form
                v-model="userInfoData"
                label-width="90px"
                :rules="rules"
            >
              <el-form-item label="头像">
                <el-upload
                    class="avatar-uploader"
                    :action="uploadUrl"
                    name="multipartFile"
                    :headers="{ 'Authorization': tokenStore.token }"
                    :auto-upload="true"
                    :show-file-list="false"
                    :on-success="uploadSuccess"
                    :before-upload="beforeUpload"
                    :disabled="isEdit===0"
                >
                  <img style="object-fit: cover;width: 130px;height: 130px;"
                       v-if="userInfoData.userPic"
                       :src="userInfoData.userPic"
                       class="avatar"
                       alt="avatar"/>
                  <el-icon v-else class="avatar-uploader-icon">
                    <Plus/>
                  </el-icon>
                </el-upload>
              </el-form-item>
              <el-form-item label="用户名" prop="username">
                <el-input v-model="userInfoData.username" :disabled="isEdit===0"></el-input>
              </el-form-item>
              <el-form-item label="邮箱">
                <el-input v-model="userInfoData.email" disabled></el-input>
              </el-form-item>
              <el-form-item label="手机/微信" prop="phone">
                <el-input v-model="userInfoData.phone" :disabled="isEdit===0"></el-input>
              </el-form-item>
              <el-form-item label="QQ号" prop="qqNumber">
                <el-input v-model="userInfoData.qqNumber" :disabled="isEdit===0"></el-input>
              </el-form-item>
              <el-form-item label="所属学校">
                <el-input v-model="userInfoData.schoolName" disabled></el-input>
              </el-form-item>
              <el-form-item label="所属院系">
                <el-input v-model="userInfoData.department" :disabled="isEdit===0"></el-input>
              </el-form-item>
              <el-form-item label="所属班级">
                <el-input v-model="userInfoData.className" :disabled="isEdit===0"></el-input>
              </el-form-item>
              <el-form-item label="注册时间">
                <el-input v-model="userInfoData.createTime" disabled></el-input>
              </el-form-item>
            </el-form>
            <div class="form-button">
              <el-button @click="goBack()">返回</el-button>
              <el-button v-if="isEdit === 0" type="primary" @click="perfectInfo">完善信息</el-button>
              <el-button v-else type="danger" @click="submitInfo()">确认修改</el-button>
            </div>
          </div>
        </el-tab-pane>
        <el-tab-pane label="修改邮箱">
          <el-form
              :model="userInfoData"
              label-width="auto"
              :rules="rules">
            <el-form-item label="原邮箱" prop="email">
              <el-input v-model="userInfoData.email" disabled></el-input>
            </el-form-item>
            <el-form-item label="新邮箱" prop="email">
              <el-input v-model="userInfoData.newEmail" placeholder="请输入新邮箱"></el-input>
            </el-form-item>
            <el-form-item label="验证码" prop="captcha">
              <el-row :gutter="20">
                <el-col :span="10">
                  <el-input placeholder="请输入验证码" v-model="userInfoData.captcha"></el-input>
                </el-col>
                <el-col :span="8">
                  <el-button v-if="!countingDown" type="primary" @click="sendCaptcha()" style="margin-left: 20px">
                    获取验证码
                  </el-button>
                  <el-button v-else type="primary" disabled>
                    {{ countdownText }}
                  </el-button>
                </el-col>
              </el-row>
            </el-form-item>
          </el-form>
          <div class="reEmail-form-button">
            <el-button @click="route.push('/')">返回</el-button>
            <el-button type="danger" @click="submitEmail()">确认修改</el-button>
          </div>
        </el-tab-pane>
      </el-tabs>
    </div>
  </div>
</template>

<style scoped>
.personal-center-container {
  width: 100%;
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;

  .tabs {
    width: 500px;
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.5);

    .info {
      width: 100%;
    }

    .form-button {
      width: 100%;
      height: 50px;
      display: flex;
      align-items: center;
      justify-content: space-between;
    }
  }
}

.avatar-uploader-icon {
  height: 130px;
  width: 130px;
}
.reEmail-form-button{
  display: flex;
  justify-content: space-between;
}
</style>